package co.fitstart.scheduler.handler.message;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.support.HttpResult;

@Component("weappMessageHandler")
public class WeappMessageHandlerImpl implements WeappMessageHandler {
	
	@Value("#{ctx['tencent.host']}")
    private String tencentHost;
	
	private static final Logger logger = LoggerFactory.getLogger(WeappMessageHandlerImpl.class);
	
	public HttpResult sendDingyueMessage(String touser, String courseName, String occurTime, String coachName, String siteName) {
		
		HttpResult result = new HttpResult();
		
        try {
        	
        	Map<String, Object> bodyParams = new HashMap<String, Object>();
    		bodyParams.put("touser", touser);
    		bodyParams.put("template_id", "qHMvm62m-7mWwIUTeip6r2dcUiPgV4D1lutXaAdhij8");
    		bodyParams.put("miniprogram_state", "formal");
    		bodyParams.put("page", "pages/profile/profile");
    		bodyParams.put("lang", "zh_CN");
    		bodyParams.put("thing4", courseName);
    		bodyParams.put("thing7", coachName);
    		bodyParams.put("time8", occurTime);
    		bodyParams.put("thing9", siteName);

    		
    		String bodyString = JsonUtils.toJsonString(bodyParams);

            Response response = Request
                .Post(new URIBuilder(tencentHost+"/dingyue-message").build())
                .connectTimeout(10000).socketTimeout(10000).bodyString(bodyString, ContentType.APPLICATION_JSON)
                .execute();

            // Get response body
            String body = response.returnContent().asString(Consts.UTF_8);
            logger.trace("WeappMessageHandlerImpl#sendDingyueMessage() - Get response body [{}].", body);
            
            result = JsonUtils.parse(body, HttpResult.class);

//            @SuppressWarnings("unchecked")
//			Map<String, Object> data = JsonUtils.parse(body, Map.class);;
//            int errcode = (Integer)data.get("errcode");
//            String errmsg = (String)data.get("errmsg");
//            result.initialize(String.valueOf(errcode), errmsg);
//
//            if (errcode != 0) {
//                logger.error("WeappMessageHandlerImpl#sendDingyueMessage() - Sending message occurs error. The error code is [{}] and error message is [{}].",errcode, errmsg);
//            }

        } catch (URISyntaxException use) {
            logger.error("WeappMessageHandlerImpl#sendDingyueMessage() - URI builder encounters syntax exception: {}", use);
            result.fail("500").message(use.getMessage());
        } catch (IOException ie) {
        	result.fail("500").message(ie.getMessage());
            logger.error("WeappMessageHandlerImpl#sendDingyueMessage() - Sending message encounters IO exception: {}", ie);
        }
        
        return result;
	}

}
